#include "dev.h"


/**
 * @brief ADC I/O初始化
 *
 */
void ADC_PortInit(void)
{
    //打开GPIO时钟
    __SYSCTRL_GPIOB_CLK_ENABLE();
    //打开ADC时钟
    __SYSCTRL_ADC_CLK_ENABLE();
    
    //Set Analog Input mode
    PB04_ANALOG_ENABLE();
    PB05_ANALOG_ENABLE();
}


/**
 * @description: ADC初始化
 * @return {*}
 */
uint32_t gCur_offset = 0;
uint32_t gVol_offset = 0;
void Adc_init(void)
{
    ADC_PortInit();   
    ADC_InitTypeDef ADC_InitStructure = {0};

    ADC_InitStructure.ADC_ClkDiv = ADC_Clk_Div8;
    ADC_InitStructure.ADC_ConvertMode = ADC_ConvertMode_Once;//ADC_ConvertMode_Once;    // 单次采样
    ADC_InitStructure.ADC_SQREns = ADC_SqrEns0to2;//ADC_SqrEns0to0;     // 单通道
    ADC_InitStructure.ADC_IN0.ADC_InputChannel = ADC_InputCH11;      /*电压*/
    ADC_InitStructure.ADC_IN0.ADC_SampTime = ADC_SampTime6Clk;

    ADC_InitStructure.ADC_IN1.ADC_InputChannel = ADC_InputCH12;      /*电流*/
    ADC_InitStructure.ADC_IN1.ADC_SampTime = ADC_SampTime6Clk;

    ADC_InitStructure.ADC_IN2.ADC_InputChannel = ADC_InputVref1P2;   /*内部电压基准：1.2V对应ADC值*/
    ADC_InitStructure.ADC_IN2.ADC_SampTime = ADC_SampTime390Clk;

    CW_ADC->CR |= ADC_CR_BGREN_Msk;

    /*延时30us 采集VBG*/
    for(uint32_t i = 0; i < 360; i++) {
        __NOP();
    }
    
    ADC_Init(&ADC_InitStructure);

    ADC_ClearITPendingAll();

    //ADC使能
    ADC_Enable();
    ADC_SoftwareStartConvCmd(ENABLE);

    // /*读取AD偏移值*/
    // for(int i = 0 ; i < 256 ; i++){
    //     ADC_ClearITPendingBit(ADC_IT_EOS);
    //     ADC_SoftwareStartConvCmd(ENABLE);
    //     while(!ADC_GetITStatus(ADC_IT_EOS));
    //     gCur_offset += CW_ADC->RESULT0;
    //     gVol_offset += CW_ADC->RESULT1;
    // }
    // gCur_offset >>= 8;
    // gVol_offset >>= 8;
}



/**
 * @description: 获取ADC值
 * @param {uint8_t} ch
 * @return {*}
 */
uint16_t Adc_Get_Value(uint8_t ch){
    ADC_ClearITPendingBit(ADC_IT_EOS);
    ADC_SoftwareStartConvCmd(ENABLE);
    while(!ADC_GetITStatus(ADC_IT_EOS));
    return ADC_GetConversionValue(ch);
}

/**
 * @description: 开始ADC转换
 * @return {*}
 */
void Start_Adc_Conv(void)
{
    ADC_ClearITPendingBit(ADC_IT_EOS);
    ADC_SoftwareStartConvCmd(ENABLE);
    while(!ADC_GetITStatus(ADC_IT_EOS));
}


